package com.itheima.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @作者 itcast
 * @创建日期 2020/10/15 14:09
 **/
@Aspect
@Component
public class WebLogAspect {
    // 定义切入点表达式
    @Pointcut("@annotation(com.itheima.aspect.WebLog)")
    public void Pointcut(){
    }

    @Around("Pointcut()")
    public Object webLogHandle(ProceedingJoinPoint joinPoint){
        Object result = null;
        try {
            // 记录请求的类名 + 方法名
            MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
            Method method = methodSignature.getMethod();
            String methodName = method.getDeclaringClass().getName() + "." + method.getName();
            // 记录请求的操作
            WebLog webLog = method.getDeclaredAnnotation(WebLog.class);
            String oparation = webLog.value();
            // 记录请求方式
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = requestAttributes.getRequest();
            String requestMethod = request.getMethod();
            // 记录请求uri
            String requestURI = request.getRequestURI();
            // 请求地址
            String remoteAddr = request.getRemoteAddr();
            // 方法的持续时长
            long startTime = System.currentTimeMillis();
            result = joinPoint.proceed();
            long endTime = System.currentTimeMillis();
            long longTime = (endTime - startTime);
            System.out.println(" -------------web接口日志  start--------------");
            System.out.println("请求的方法名: " + methodName);
            System.out.println("请求的方式: " + requestMethod);
            System.out.println("请求的uri: " + requestURI);
            System.out.println("请求的操作: " + oparation);
            System.out.println("方法持续时长: " + longTime);
            System.out.println("请求的IP地址: " + remoteAddr);
            System.out.println(" -------------web接口日志  end--------------");
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return result;
    }

}
